package com.tornado.community.service;

import com.tornado.community.advice.Constant;
import com.tornado.community.dto.CommentDto;
import com.tornado.community.mapper.CommentMapper;
import com.tornado.community.mapper.UserMapper;
import com.tornado.community.model.Comment;
import com.tornado.community.model.CommentExample;
import com.tornado.community.model.User;
import com.tornado.community.model.UserExample;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService {
    private final CommentMapper commentMapper;
    private final UserMapper userMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public CommentService(CommentMapper commentMapper, UserMapper userMapper) {
        this.commentMapper = commentMapper;
        this.userMapper = userMapper;
    }

    public List<CommentDto> selectQuestionComment(int questionId) {
        return this.selectCommentList(Constant.CommentType.QUESTION, questionId);
    }

    public List<CommentDto> selectCommentComment(long commentId) {
        return this.selectCommentList(Constant.CommentType.COMMENT, commentId);
    }

    private List<CommentDto> selectCommentList(int type, long parentId) {
        //查出某问题下的所有评论
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria()
                .andParentIdEqualTo(parentId)
                .andTypeEqualTo(type);
        List<Comment> commentList = commentMapper.selectByExample(commentExample);
        if (commentList.isEmpty()){
            return new ArrayList<>();
        }
        //根据评论查出所有用户
        List<Integer> commenter = commentList.stream().map(Comment::getCommenter).distinct().collect(Collectors.toList());
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdIn(commenter);
        Map<Integer, User> userMap = userMapper.selectByExample(userExample).stream().collect(Collectors.toMap(User::getId, user -> user));
        //返回评论DTO
        return commentList.stream().map(comment -> {
            CommentDto commentDto = new CommentDto();
            BeanUtils.copyProperties(comment, commentDto);
            commentDto.setUser(userMap.get(comment.getCommenter()));
            return commentDto;
        }).collect(Collectors.toList());
    }
}
